SharePointList using SharePoint Web Service


Introduction

Depending on business requirements sometimes we tend to implement the best of all technologies and end up aligning many heterogeneous technologies. If they need these systems to communicate among themselves then we need to contrive a platform independent protocol so that it can be easily decoded into their respective dialects. Web services equipped with SOAP protocol are one of those solutions.

In these days SharePoint is used extensively by organizations as a collaborative platform. Sometimes other systems need to integrate with SharePoint for their array of actions and in terms of business continuity. SharePoint is equipped with many Web Services (you will find them under one roof i.e. _vti_vin) which can be accessed and consumed by other applications for the sake of collaboration and communication.

Though there are many web services (packed with many web methods) exposed by a  SharePoint server, none of them are covered extensively. Here is my effort to cover some of the these Web methods available in a web service(List web service) illustrating how these can be used in tandem to accomplish a technical requirement.

Overview

Unless a SharePoint site is anonymously accessible we have to pass a valid user credential that has access to the web service (otherwise we can access it with the Default credential). To store a user credential, a resource file (Resource1.resx) is added to the project( because it is very easy to read an embedded resource file, of course).

Besides that, a user input form is there (see figure-1) which accepts a Site URL and a list name as user input. Then using the below web methods, it reads the list and displays data in a GridView control.

[Definition and description of parameters of the web method GetListItems is interpreted in the below table.]

GetListItems(string listName, string viewName, XmlNode query, XmlNode viewFields, string rowLimit, XmlNode queryOptions, string webSiteId )

String listName (Mandatory)

Accepts GUID of List only. If you are aware about the GUID then fine. Otherwise you can get it by calling web method "GetListCollection()" of List web service. See code for illustration.

String viewName (optional)

Accepts GUID of View only. If passed empty or null, default view is queried.

XmlNode query (optional)

In case there is no condition, pass XmlNode object with "Query" as tagname. For detail refer code.

XmlNode viewFields (optional)

In case you want to see all columns then build an XmlNode object with "ViewFields" as tagname and pass it as parameter. We are using web method "GetListAndView" to get all user defined columns.

String rowLimit(optional)

To view all rows set "rowLimit" to string.Empty. Otherwise pass the number of rows you want see. In case no. of rows available in list is lesser than the rowLimit defined by you, all records are fetched.

XmlNode queryOptions(optional)

In case there is no condition simple pass XmlNode object with "QueryOptions" as tag name. For detail refer code where it is defined.

String webSiteId(optional)

If string.Empty is passed, then default site is queried. Otherwise site with given GUID is searched for.

shrpntList.gif

Figure 1

Description

As a prerequisite, you need to have VS2010 or VS Framework 3.5 or more to run this project. The project is developed and tested with SharePoint 2007.

After giving the SharePoint site URL and a list name in user interface and when the user clicks the "submit" button (refer Figure-1), the SharePoint Server is queried by its web service and results are returned back to the windows application. After that a dataset is generated out of the XML returned by the web service and bound to a GridView control. It is described comprehensively below.

  • All actions occur in response to the button click. Associated event is "buttonSubmit_Click".
  • First it accepts the User given SiteUrl and List name.
  • Call the function "LoadAppResource()" to load the user credential from resource file. If the site is anonymously accessible then pass the default credential (System.Net.CredentialCache.DefaultCredentials).
  • Call the web method "GetListCollection()" of List webservice to get the GUID of the list. The user only needs to provide the List Name, however, the GetListItems() web method needs a GUID as the parameter.
  • Call the web method "GetListAndView()" to get a list of columns marked as viewable in the default view. This column list will be passed as a parameter to the web method GetListItems().
  • Call the web method GetListItems() with all required parameters and generate a dataset with the XML returned by the web method.
  • Bind that dataset to a GridView control to display the final results.

Refer below code snippet for further details.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ManageListItems.ManageList;
using System.Reflection;
using System.Resources;
using System.Collections;
using System.Globalization;

namespace ManageListItems
{
    public partial class Form1 : Form
    {
        ManageList.Lists listService;
        string url = string.Empty;
        string listName = string.Empty;
        string listGuid = string.Empty;
        string userName = string.Empty;
        string password = string.Empty;
        string domain = string.Empty;
        string rowLimit = "";

        public Form1()
        {
            InitializeComponent();

            listService = new Lists();
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            url = textBoxURL.Text;
            listName = textBoxListName.Text;
            listService.Url = url + "/_vti_bin/Lists.asmx";

            try
            {
                LoadAppResource(); //Loades username, password, domain from resource file
                listService.Credentials = new System.Net.NetworkCredential(userName, password, domain);
                //listService.Credentials = System.Net.CredentialCache.DefaultCredentials;  // if Site is annonymously accessible
                //Get List GUID, GetListItem webmethod needs GUID of the List to retrieve items
                XmlNode lists = listService.GetListCollection();
                foreach (XmlNode list in lists)
                {
                    if (list.Attributes["Title"].Value == listName)
                    {
                        listGuid = list.Attributes["ID"].Value;
                        break;
                    }

                }

                //Automating the process of getting display columns by using WebMethod GetListAndView...
               
//Get Display Columns of the View(that is default view)

                System.Xml.XmlNode nodeViewListView = listService.GetListAndView(listName, string.Empty); //second argument is empty because
                                                                                   
//we are querying for default view. Other wise pass GUID of the View to query for specific view

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(nodeViewListView.OuterXml);

                XmlNodeList xnList = xmlDoc.GetElementsByTagName("ViewFields"); //returns all columns associated with the default view

                xmlDoc = new System.Xml.XmlDocument();
                System.Xml.XmlElement query = xmlDoc.CreateElement("Query");

                System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");

                XmlNode nodes = xnList.Item(0);
                string queryInnerXml = string.Empty;

                for (int i = 0; i < nodes.ChildNodes.Count; i++)// looping to get all display coulumns associatef with the view
                {
                    if (nodes.ChildNodes[i].Attributes["Name"].Value != "Edit") // We do not need Edit column
                    {
                        queryInnerXml += "<FieldRef Name=\"" + nodes.ChildNodes[i].Attributes["Name"].Value +
"\" />";
 
                    }
 
                }

                viewFields.InnerXml = queryInnerXml.Trim(); //associating with view fields query
                System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
                queryOptions.InnerXml = "<IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns>";

                System.Xml.XmlNode nodeListItems =
                    listService.GetListItems(listName, string.Empty, query, viewFields, rowLimit, queryOptions, null);

                System.IO.StringReader xmlSR = new System.IO.StringReader(nodeListItems.InnerXml);//creating
string reader to get XML and load it to get a dataset object
 
                DataSet dsList = new DataSet();

                dsList.ReadXml(xmlSR);
                dataGridView1.DataSource = dsList.Tables[1];
            }
            catch (Exception ex1)
            {
                MessageBox.Show(ex1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }           

        }
        private void LoadAppResource()
        {
            ResourceSet resourceSet;
            resourceSet = ManageListItems.Resource1.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);

            foreach (DictionaryEntry d in resourceSet)
            {
                if ((string)d.Key == "Username")
                    userName = (string)d.Value;

                if ((string)d.Key == "Password")
                    password = (string)d.Value;

                if ((string)d.Key == "Domain")
                    domain = (string)d.Value;
           
            }
       
        }
    }
}


Conclusion

A developer's life would never have been so easy unless SharePoint was packed up with these web services. I will keep on posting one by one, but if you want to realize the power of SharePoint Web services try them with InfoPath!
 

Up Next
    Ebook Download
    View all
    Learn
    View all